<?php
	include 'logincheck.php';
	include 'connect.php';
	
	$title = mysql_real_escape_string($_POST['title']);
	$postBody = mysql_real_escape_string($_POST['text']);
	$category = $_POST['cat'];
	$id = $_POST['id'];
	
	/*
	$mysql_host = "mysql11.000webhost.com";
	$mysql_database = "a4482850_test";
	$mysql_user = "a4482850_test";
	$mysql_password = "kunju.261371";
	*/
	
	//This function is used to generate clean urls
	setlocale(LC_ALL, 'en_US.UTF8');
	function toAscii($str, $replace=array(), $delimiter='-') {
	if( !empty($replace) ) {
			$str = str_replace((array)$replace, ' ', $str);
	}

			$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
			$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
			$clean = strtolower(trim($clean, '-'));
			$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

			return $clean;
	}
	
	//update the content
	mysql_select_db($db, $con);
	
	//newpost
	if ( $id == 0 ){
		$url = toAscii($title);
		$sqlQuery = "INSERT INTO {$table} (Name, Date, URL, Category, postBody) VALUES ('{$title}', CURDATE(), '{$url}', '{$category}', '{$postBody}')";
		$retval = mysql_query($sqlQuery);
		$id = mysql_insert_id();
		echo "<script>window.location.href = 'post?id={$id}'</script>";
	//update post
	} else {
		$sqlQuery = "UPDATE {$table} SET Name='{$title}', postBody = '{$postBody}' WHERE ID = $id";
		$retval = mysql_query($sqlQuery);
	}
	
	//check whether save/update was successful
	if(! $retval )
	{
		die('Could not enter data: ' . mysql_error());
	}
	
	//if save/update was successful, upadte the search index also
	$query  = "SELECT * FROM {$table} ORDER BY ID DESC";
	$result = mysql_query($query) or die(mysql_error());
	$str = "";

	while($row = mysql_fetch_assoc($result)) {
		$url = $row['URL']."_id_".$row['ID'];
		
		$str = $str."\n<a href='".$url."'><div class='entry'>"
			 ."<h4 class='titles'>".$row['Name']."</h4></div></a>\n";
	}
	
	file_put_contents('searchDB.php', $str);
	
	echo "Data saved successfully\n";

	mysql_close($con);
?>